import {
  getDefaultXieyi,
  getXieyiById
} from '../../api/live'
var uploadImage = require('../../utils/uploadFile')
// components/autograph/index.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    width: {
      type: String,
      value: '100%'
    },
    height: {
      type: String,
      value: '400rpx'
    },
    lineWidth: {
      type: Number,
      value: 2
    },
    lineColor: {
      type: String,
      value: '#000000'
    },
    xieyiId:{
      type:String | undefined ,
      value:""
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    type:1,//1金石  2现金
    show: false,
    isDraw: !false, // 是否能画画
    canvasElement: null,
    canvasContext: null,
    oldPosition: {
      x: 0,
      y: 0
    },
    html: "",
    showDialog: false,
  },

  /**
   * 组件的方法列表
   */
  methods: {
    handleGetXieyi() {
      this.setData({
        showDialog: true
      })
      console.log(this.properties.xieyiId)
      getXieyiById({courseId:this.properties.xieyiId}).then(res => {
        if (res) {
          this.setData({
            html: res
          })
        }
      })
    },
    open() {
      this.setData({
        show: true
      })
    },
    close() {
      this.setData({
        show: false,
        isDraw: true
      })
      this.clearCanvas()
      this.triggerEvent('closeWrite', true)
    },
    // 初始化canvas
    initCanvas(fn) {
      const query = wx.createSelectorQuery().in(this)
      query.select('.autograph-canvas').fields({
        node: true,
        size: true,
        context: true
      }).exec(res => {

        const canvas = res[0].node
        const context = canvas.getContext('2d')
        const dpr = wx.getSystemInfoSync().pixelRatio

        canvas.width = res[0].width * dpr
        canvas.height = res[0].height * dpr
        context.scale(dpr, dpr)
        this.setData({
          canvasElement: canvas,
          canvasContext: context
        }, function () {
          if (typeof fn == 'function') {
            fn()
          }
        })
      })
    },
    // 描绘canvas
    drawCanvas(position) {
      if (this.data.canvasContext) {

        this.data.canvasContext.strokeStyle = this.properties.lineColor
        this.data.canvasContext.lineWidth = this.properties.lineWidth

        this.data.canvasContext.beginPath()
        this.data.canvasContext.moveTo(this.data.oldPosition.x, this.data.oldPosition.y)
        this.data.canvasContext.lineTo(position.x, position.y)
        this.data.canvasContext.stroke()
        this.data.canvasContext.closePath()
        this.setData({
          oldPosition: {
            x: position.x,
            y: position.y
          }
        })
      }
    },
    // 在画布触摸开始
    handleTouchStart(e) {
      console.log(e)
      const x = e.touches[0].x;
      const y = e.touches[0].y;
      this.setData({
        oldPosition: {
          x: x,
          y: y
        },
        isDraw: true
      })
    },
    // 在画布触摸移动
    handleTouchMove(e) {
      if (this.data.isDraw) {
        let positionItem = e.touches[0]
        if (this.data.canvasContext) {
          this.drawCanvas(positionItem, true)
        } else {
          this.initCanvas(() => {
            this.drawCanvas(positionItem, true)
          })
        }
      }
    },
    // 在画布触摸结束
    handleTouchEnd() {
      this.setData({
        isDraw: false
      })
    },
    // 清除画布
    clearCanvas() {
      const x = this.data.canvasElement && this.data.canvasElement.width
      const y = this.data.canvasElement && this.data.canvasElement.height
      this.data.canvasContext && this.data.canvasContext.clearRect(0, 0, x, y)
    },
    // 获取画布的base64
    getCanvasBase64() {
      const pngPic = this.data.canvasElement.toDataURL()
      console.log(this.data.canvasElement.toBlob)
      console.log(pngPic,'------签名base64')
      return pngPic
    },

    formatTime(date) {
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const day = date.getDate()
      const hour = date.getHours()
      const minute = date.getMinutes()
      const second = date.getSeconds()

      return [year, month, day].map(this.formatNumber).join('-')
    },
    formatNumber(n) {
      n = n.toString()
      return n[1] ? n : '0' + n
    },
    // 获取临时文件
    getCavasTempFile() {
      const _this = this
      return new Promise((resolve, reject) => {
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          canvas: this.data.canvasElement,
          success: (res) => {
            console.log(res, 'xx');
            var nowTime = this.formatTime(new Date());
            uploadImage(res.tempFilePath, 'cbb/' + nowTime + '/',
              function (result) {
                console.log("======上传成功图片地址为：", result);
                wx.hideLoading();
                // 开始购买流程
                if(_this.data.type==1){
                  _this.triggerEvent('buy', result)
                }else{
                  _this.triggerEvent('cashbuy', result)
                }
              },
              function (result) {
                console.log("======上传失败======", result);
                wx.hideLoading()
              }
            )
          },
          fail: () => {
            wx.showToast({
              title: '签名生成失败，请重签',
              icon: 'none'
            })
            reject('图片临时文件生成失败')
          }
        })
      })
    },
    handleCloseXieyi(){
      this.setData({
        showDialog:false
      })
    }
  }
})